package com.example.servlet;


import com.example.Service.UserService;
import com.example.pojo.User;
import com.google.gson.Gson;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }
    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 与 doGet/doPost 中的跨域配置完全一致
        resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 在 doGet/doPost 方法开头添加
        resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
// 例如前端地址是 http://127.0.0.1:5500，则写这个地址，不能用 *（否则无法携带 Cookie）
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        resp.setHeader("Access-Control-Allow-Credentials", "true"); // 允许携带 Cookie

        BufferedReader br = new BufferedReader(req.getReader());
        StringBuffer sbuffer =new  StringBuffer();
        String s="";
        while ((s=br.readLine())!=null){
            sbuffer.append(s);
        }
        System.out.println(sbuffer.toString());
        Gson gson =new Gson();
//        User user =gson.fromJson(sbuffer.toString(),User.class);
        Map<String, String> requestData = gson.fromJson(sbuffer.toString(), Map.class);

        // 从解析的Map中获取数据
        String userId = requestData.get("userId");
        String userPwd = requestData.get("userPwd");
        String num2 = requestData.get("checkNum"); // 从Map中获取验证码

        // 创建User对象
        User user = new User();
        user.setUserId(userId);
        user.setUserPwd(userPwd);
        //取出保存的验证码
        HttpSession session=req.getSession();
        System.out.println(session.getId());
        System.out.println(session.getAttribute("checkNum"));
        String num1=(String)session.getAttribute("checkNum");//获取session中保存的验证码
//        String num2=req.getParameter("checkNum");//获取用户输入的验证码
        System.out.println(num1);
        System.out.println(num2);
        Map<String,Object> map=new HashMap<>();

        if (num1.equals(num2)){
            UserService userService=new UserService();//调用业务逻辑完成登录验证
            User u =userService.check_login(user);
            if (u!=null){
                map.put("code",200);
                map.put("msg","登录成功");
                map.put("data",u);
            }else {
                map.put("code",500);
                map.put("msg","账号密码错误");
            }

        }else {
            map.put("code",500);
            map.put("msg","验证码错误");
        }
        String json =gson.toJson(map);
        resp.getWriter().append(json);
    }

    public void destroy() {
    }
}
